#include "Widget.h"
#include "ui_Widget.h"

#include <QMessageBox>
#include <QFileDialog>
#include <QTextStream>
#include <QCloseEvent>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    _windowTitleName("Calenton - "),
    _windowTitleChanged(""),
    _windowTitleSaved("Untitled"),
    ui(new Ui::Widget),
    _flagYesNo(false)
{
    ui->setupUi(this);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_addButton_clicked()
{
    ui->taskEdit->setFocus();

    QString name = ui->taskEdit->text();
    if (name.isEmpty() == false) {
        addItemToList(name);
        emit hasListChanged(true);
    }
}

void Widget::on_deleteButton_clicked()
{
    QList<QTreeWidgetItem *> selectedItems = ui->taskList->selectedItems();
    if (selectedItems.isEmpty() != true) {
        QTreeWidgetItem *selectedItem = selectedItems.first();
        delete selectedItem;
        emit hasListChanged(true);
    }
}

void Widget::on_doneButton_clicked()
{
    QList<QTreeWidgetItem *> selectedItems = ui->taskList->selectedItems();
    if (selectedItems.isEmpty() != true) {
        QTreeWidgetItem *selectedItem = selectedItems.first();
        QString mark = selectedItem->text(1);
        if (mark == "X")
            selectedItem->setText(1, " ");
        else
            selectedItem->setText(1, "X");
        emit hasListChanged(true);
    }
}

void Widget::on_saveButton_clicked()
{
    if (saved() == true) {
        emit hasListChanged(false);
        emit hasListSaved(true);
    }
}

void Widget::on_loadButton_clicked()
{
    if (wantContinue() == true) {
        QString path = QFileDialog::getOpenFileName(this, "Open File");
        if (path.isNull() != true) {
            _filePath = path;
            if (loadList(_filePath) == true) {
                emit hasListChanged(false);
                emit hasListSaved(true);
            }
            else {
                QMessageBox::critical(this, "Error", "Calenton can not load the file.", QMessageBox::Ok, QMessageBox::Ok);
            }
        }
        else if (_flagYesNo == true) {
            emit hasListChanged(false);
            emit hasListSaved(true);
            _flagYesNo = false;
        }
    }
}

void Widget::showHasListChanged(bool changed)
{
    if (changed == true)
        _windowTitleChanged = "*";
    else
        _windowTitleChanged = "";

    this->setWindowTitle(_windowTitleName + _windowTitleChanged + _windowTitleSaved);
}

void Widget::showHasListSaved(bool saved)
{
    if (saved == true)
        _windowTitleSaved = _filePath.right(_filePath.length() - _filePath.lastIndexOf("/") - 1);
    else
        _windowTitleSaved = "Untitled";

    this->setWindowTitle(_windowTitleName + _windowTitleChanged + _windowTitleSaved);
}

void Widget::addItemToList(QString name, bool checked)
{
    if (name.isEmpty() != true)
    {
        QTreeWidgetItem *newItem = new QTreeWidgetItem(QStringList(name));
        newItem->setTextAlignment(1, Qt::AlignHCenter);
        if (checked == true)
            newItem->setText(1, "X");
        else
            newItem->setText(1, " ");

        QList<QTreeWidgetItem *> selectedItems = ui->taskList->selectedItems();
        if (selectedItems.isEmpty() != true)
        {
            QTreeWidgetItem *selectedItem = selectedItems.first();
            int index = ui->taskList->indexOfTopLevelItem(selectedItem);
            ui->taskList->insertTopLevelItem(index + 1, newItem);
        }
        else
        {
            ui->taskList->addTopLevelItem(newItem);
        }
    }
}

bool Widget::wantContinue()
{
    if (_windowTitleChanged != "*")
        return true;

    int question = QMessageBox::question(this,
                                         "The list has been modified",
                                         "Do you want to save your changes?",
                                         QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel,
                                         QMessageBox::Save);
    switch (question)
    {
        case QMessageBox::Save:
            if (saved() == false)
                return false;
            _flagYesNo = true;
        case QMessageBox::Discard:
            break;
        case QMessageBox::Cancel:
            return false;
    }
    return true;
}

bool Widget::saved()
{
    if (_windowTitleSaved == "Untitled") {
        QString path = QFileDialog::getSaveFileName(this, "Save File As");
        if (path.isNull() == true)
            return false;

        _filePath = path;
    }

    if (saveList(_filePath) == false)
        return false;

    return true;
}

bool Widget::saveList(QString path)
{
    QFile file(path);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
        return false;

    QTextStream out(&file);
    for (int i = 0; i < ui->taskList->topLevelItemCount(); i++) {
        QString name = ui->taskList->topLevelItem(i)->text(0);
        QString mark = ui->taskList->topLevelItem(i)->text(1);
        out << name << " " << mark << endl;

    }

    file.close();
    return true;
}

bool Widget::loadList(QString path)
{
    QFile file(path);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
        return false;

    QTextStream in(&file);
    QString line = in.readLine();
    if (line.isNull() == true)
        return false;

    QList<QString> names;
    QList<bool> marks;
    while (line.isNull() == false) {
        QString name = line.left(line.length() - 2);
        QString mark = line.right(1);
        bool flag = false;
        if (mark == "X")
            flag = true;
        else if (mark != " ")
            return false;
        names.push_back(name);
        marks.push_back(flag);
        line = in.readLine();
    }
    file.close();

    ui->taskList->clear();

    for (int i = 0; i < names.length(); i++) {
        addItemToList(names.at(i), marks.at(i));
    }

    return true;
}

void Widget::closeEvent(QCloseEvent *event)
{
    if (wantContinue() == true)
        event->accept();
    else
        event->ignore();
}
